<script setup>
import { ref } from 'vue';
import { useLogStore } from "@/stores/logStore.js";
import { ElMessage } from "element-plus";

const logStore = useLogStore();
const dialogVisible = ref(false);
const currentLogId = ref(null);

// 格式化JSON详情
const formatDetail = (detail) => {
  try {
    const parsed = JSON.parse(detail);
    return typeof parsed === 'object' ? JSON.stringify(parsed, null, 2) : detail;
  } catch {
    return detail;
  }
};

// 显示对话框
const show = (logId) => {
  currentLogId.value = logId;
  dialogVisible.value = true;
  logStore.getLogDetail(logId);
};

// 关闭对话框
const close = () => {
  dialogVisible.value = false;
};

// 暴露show方法
defineExpose({ show });
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      title="日志详情"
      width="60%"
      @close="close"
  >
    <el-descriptions :column="1" border v-if="logStore.logDetail">
      <el-descriptions-item label="日志ID">{{ logStore.logDetail.id }}</el-descriptions-item>
      <el-descriptions-item label="用户ID">{{ logStore.logDetail.userId }}</el-descriptions-item>
      <el-descriptions-item label="操作类型">{{ logStore.logDetail.action }}</el-descriptions-item>
      <el-descriptions-item label="目标类型">{{ logStore.logDetail.targetType }}</el-descriptions-item>
      <el-descriptions-item label="目标ID">{{ logStore.logDetail.targetId }}</el-descriptions-item>
      <el-descriptions-item label="IP地址">{{ logStore.logDetail.ip }}</el-descriptions-item>
      <el-descriptions-item label="操作时间">{{ logStore.logDetail.createdTime }}</el-descriptions-item>

      <el-descriptions-item label="变更详情">
        <pre class="log-detail">{{ formatDetail(logStore.logDetail.detail) }}</pre>
      </el-descriptions-item>
    </el-descriptions>

    <template #footer>
      <el-button @click="close">关闭</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.log-detail {
  max-height: 300px;
  overflow: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>